﻿using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AuthenticationAPI.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using AuthenticationAPI.Models.DbContext;
using System.Collections.Generic;
using AuthenticationAPI.Models.Utility;


namespace AuthenticationAPI.Controllers
{
    public class AuthorizeProjectController : ApiController
    {
        [Route("api/AuthorizedProjects/{userName}")]
        [HttpGet]
        public HttpResponseMessage AuthorizeUserProjects(string userName)
        {
            var prjList = UserHelper.GetAuthorizedProjects(userName);
            return Request.CreateResponse(HttpStatusCode.OK, prjList);

        }

        [Route("api/AuthorizedProjectsType/{userName}")]
        [HttpGet]
        public HttpResponseMessage AuthorizeProjectTypes(string userName)
        {
            var list = UserHelper.GetAuthorizedProjectTypes(userName).Select(t => new
            {
                typeCode = t.ProjectType,
                typeName = t.Name
            }).ToList();

            return Request.CreateResponse(HttpStatusCode.OK, list);

        }


        [Route("api/AuthorizedProjects/{userName}")]
        [HttpPost]
        public HttpResponseMessage UpdateAuthorizeUserProjects(string userName, [FromBody]string jsonStr)
        {
            var list = JsonConvert.DeserializeObject<List<int>>(jsonStr);
            using (var db = new AuthenticationEntities())
            {
                var exsited = db.AuthorizedProject.Where(p => p.UserName == userName);
                db.AuthorizedProject.RemoveRange(exsited);
                var newList = (from p in list
                               select new AuthorizedProject()
                               {
                                   UserName = userName,
                                   PrjId = p,
                                   Operation = ""
                               }).ToList();
                db.AuthorizedProject.AddRange(newList);
                db.SaveChanges();
            }
            return Request.CreateResponse(HttpStatusCode.OK, true);
        }
    }
}